package developer.核心类.锁;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangyongkang
 * @time 2025/7/21 19:52
 * @description
 */
public class Lock {

    public static void main(String[] args) throws InterruptedException {

        ReentrantLock lock = new ReentrantLock();
        lock.newCondition();

        lock.lock();
        lock.unlock();
        CountDownLatch countDownLatch = new CountDownLatch(2);
        countDownLatch.countDown();

        Sync sync = new Sync();

        new Thread(() -> {
            sync.lock();
            System.out.println("你好");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            sync.unlock();
        }).start();

        TimeUnit.SECONDS.sleep(1);


        new Thread(() -> {
            System.out.println("开始阻塞");
            sync.lock();
            System.out.println("你好");
            sync.unlock();
        }).start();


    }

    static class Sync extends AbstractQueuedSynchronizer {
        public void lock() {
            acquire(1);
        }

        @Override
        protected boolean tryAcquire(int arg) {
            if (getState() == 0) {
                setState(arg);
                return true;
            } else {
                return false;
            }

        }

        public void unlock() {
            release(0);
        }

        @Override
        protected boolean tryRelease(int arg) {
            if (getState() == 1) {
                setState(0);
                return true;
            }
            return false;

        }
    }
}
